package cn.tedu.lucky.draw.server.service.impl;

import cn.tedu.lucky.draw.server.common.enums.DrawEnum;
import cn.tedu.lucky.draw.server.common.enums.ErrorEnum;
import cn.tedu.lucky.draw.server.common.handler.DrawException;
import cn.tedu.lucky.draw.server.protocol.po.ActivityPrize;
import cn.tedu.lucky.draw.server.protocol.po.Prize;
import cn.tedu.lucky.draw.server.protocol.query.PrizeQuery;
import cn.tedu.lucky.draw.server.repository.ActivityPrizeRepository;
import cn.tedu.lucky.draw.server.repository.PrizeRepository;
import cn.tedu.lucky.draw.server.service.IPrizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PrizeServiceImpl implements IPrizeService {

    @Autowired
    private PrizeRepository prizeRepository;
    @Autowired
    private ActivityPrizeRepository activityPrizeRepository;


    List<Prize> prizeList;

    @Override
    public List<Prize> findAll(PrizeQuery prizeQuery) {
        if(prizeList == null){
            prizeList = prizeRepository.findAll();
        }

//  过滤收到的Query
        String name = prizeQuery.getName();
        Integer status = prizeQuery.getStatus();
//  Stream()过滤
        List<Prize> collect = prizeList.stream()
                .filter(prize -> (name == null || name.equals(prize.getName())))
                .filter(prize -> (status == null || status.equals(prize.getStatus())))
                .collect(Collectors.toList());
        //过滤name,status = > 收集新结果集

        return collect;
    }

    @Override
    public void save(Prize prize) {
        LocalDateTime now = LocalDateTime.now();
        prize.setCreateTime(now);
        prize.setUpdateTime(now);
        Prize save = prizeRepository.save(prize);
        if(save == null){
            throw new DrawException(ErrorEnum.SYSTEM_ERROR);
        }
        prizeList = null;
    }

    @Override
    public List<Prize> findAllByActivityId(Long id) {
        List<ActivityPrize> activityPrizes = activityPrizeRepository.findByActivityId(id);
        List<Long> prizeIds = activityPrizes.stream().map(activityPrize -> activityPrize.getPrizeId()).collect(Collectors.toList());
        return prizeRepository.findAllById(prizeIds);
    }

    @Override
    public List<Prize> findNoBindPrizeByActivityId(Long id) {
        List<ActivityPrize> activityPrizes = activityPrizeRepository.findByActivityId(id);
        List<Long> excludeIds = activityPrizes.stream().map(activityPrize -> activityPrize.getPrizeId()).collect(Collectors.toList());
        Integer status = Integer.valueOf(DrawEnum.ENABLE.getCode());
        if(excludeIds.size()>0){
            return prizeRepository.findByIdNotInAndStatus(excludeIds,status);
        }
        return prizeRepository.findByStatus(status);
    }
}
